<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\MasterOrderRefund;
use App\Events\OrderRefunded;
use App\Models\OrderRefund;
use App\Models\OrderStatus;
use App\Notifications\OrderNotifications\OrderRefundNotification;
use App\Services\ISystemService;
use DB;
use Illuminate\Cache\Events\CacheHit;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class MasterOrderRefundListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'finance';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CacheHit  $event
     * @return void
     */
    public function handle(MasterOrderRefund $event)
    {
        $refund = OrderRefund::find($event->refund_id);
        if(!$refund){
            throw new \Exception('miss refund');
        }

        if ($refund->refund_result_type == Params::ORDER_REFUND_RESULT_AGREE){
            if ($refund->refund_type == Params::ORDER_REFUND_FULL){
                $ret = OrderStatus::where('order_id',$refund->order_id)->take(1)->update([
                    'except_status'=>Params::ORDER_EXCEPT_REFUNDED,
                    'refund_status'=>Params::ORDER_REFUND_RETURN_FULL,
                ]);
            }else if ($refund->refund_type == Params::ORDER_REFUND_PART){
                $ret = OrderStatus::where('order_id',$refund->order_id)->take(1)->update([
                    'except_status'=>Params::ORDER_EXCEPT_NORMAL,
                    'refund_status'=>Params::ORDER_REFUND_RETURN_PART,
                ]);
            }else{
                $ret = false;
            }
            if (!$ret){
                throw new \Exception('order status update fail');
            }

            $ret = event(new OrderRefunded($refund->id,$refund->refund_amount));
            if (!$ret){
                throw new \Exception('event trigger fail');
            }
        }

        $refund->order->merchant->notify(new OrderRefundNotification($refund));
    }

    public function failed(MasterOrderRefund $event, \Exception $exception)
    {
        //
    }
}
